<?php
/**
 *
 * @author Martin "DevelX" Jurča
 */
class PayPal extends Module {
    protected $name = 'PayPal';
    protected $administrable = false;
    protected $version = '2010-06-14';
    protected $details = array('dependencies' => array(),
            'observes' => array('PayPal'));

    protected $paymentType = 6;
    protected $email = 'info@clicker.cz';

    public function __construct(DBAPI $dbapi, RecordList $recordList) {
        parent::__construct($dbapi, $recordList);
    }

    public function install() {
        return true;
    }

    public function uninstall() {
        return true;
    }

    public function success($order, $key = false) {
        $user = Modules::getModule('Users')->getUser();
        $order = Modules::getModule('Orders')->getOrderData($order);
        $result = $this->checkPaymentStatus();
        if ($result == 1) {
            Modules::getModule('Orders')->resolveOrder($order['id']);
            $this->addMsg('paymentSuccess', self::MSG_CONFIRM);
        } else {
            $this->addMsg('paymentConfirmationError', self::MSG_ERROR);
        }
    }

    public function fail() {
        $this->addMsg('paymentError', self::MSG_ERROR);
    }

    public function redirectToPayment($amount, $credits, $uid, $note) {
        $amount = (int) $amount;
        $orderId = Modules::getModule('Orders')->createOrder($uid, $credits,
                $this->paymentType, $note, $amount);
        $params = array('credits' => $credits);
        $params = array('orderId' => $orderId, 'email' => $this->email,
                'itemName' => $this->lang('itemName', $params), 'amount' =>
                $amount);
        $this->template('redirect', $params);
        exit();
    }

    private function checkPaymentStatus($order) {
        // read the post from PayPal system and add 'cmd'
        $req = 'cmd=_notify-validate';

        foreach ($_POST as $key => $value) {
            $value = urlencode(stripslashes($value));
            $req .= "&$key=$value";
        }

        // post back to PayPal system to validate
        $header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
        $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
        $fp = fsockopen('ssl://www.paypal.com', 443, $errno, $errstr, 30);

        // assign posted variables to local variables
        $item_name = $_POST['item_name'];
        $item_number = $_POST['item_number'];
        $payment_status = $_POST['payment_status'];
        $payment_amount = $_POST['mc_gross'];
        $payment_currency = $_POST['mc_currency'];
        $txn_id = $_POST['txn_id'];
        $receiver_email = $_POST['receiver_email'];
        $payer_email = $_POST['payer_email'];

        if (!$fp) {
            return -1;
        } else {
            fputs ($fp, $header . $req);
            while (!feof($fp)) {
                $res = fgets ($fp, 1024);
                if (strcmp($res, "VERIFIED") == 0) {
                    // check the payment_status is Completed
                    // check that txn_id has not been previously processed
                    if ($receiver_email != $this->email) {
                        return -2;
                    }
                    if (($payment_currency != 'CZK') ||
                            ($payment_amount != $order['amount'])) {
                        return -3;
                    }
                    if ($item_number != $order['id']) {
                        return -4;
                    }
                    return 1;
                } else if (strcmp($res, "INVALID") == 0) {
                    return 0;
                }
            }
            fclose ($fp);
        }
    }
}
?>
